import { Component, OnInit } from '@angular/core';
import { environment } from '../../../environments/environment';
import { HttpClient } from '@angular/common/http';
import * as _ from 'lodash';
import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';

@Component({
  selector: 'app-greenworks',
  templateUrl: './greenworks.component.html',
  styleUrls: ['./greenworks.component.scss'],
})
export class GreenworksComponent implements OnInit {
  greenworks: any;
  resolver: any;
  lists: any[] = [];

  constructor(
      private http: HttpClient,
  ) {
  }

  ngOnInit(): void {
    this.resolveGreenworks();
    this.initGreenworkTypes();
  }

  private resolveGreenworks() {
    this.greenworks = nw.require(`${environment.assetsPath}/steam/greenworks`);
    console.log('greenworks', this.greenworks);
    let result = JSON.parse(JSON.stringify(this.greenworks, (k: any, v: any) => {
      if (typeof v === 'function') {
        return 'function';
      }
      return v;
    }));
    this.resolver = Object.keys(result).map(key => ({key, value: result[key]}));
    // let check1 = (s: any) => s.value === 'function';
    // let check2 = (s: any) => typeof s.value === 'object';
    //
    // let r1 = _.filter(all, s => check1(s));
    // let r2 = _.filter(all, s => check2(s));
    // let r0 = _.filter(all, s => !check1(s) && !check2(s));
    //
    // let sorter = (s: any) => s.key.toLowerCase();
    // this.resolver = {
    //   functions: _.sortBy(r1, sorter),
    //   objects: _.sortBy(r2, sorter),
    //   others: _.sortBy(r0, sorter),
    // };

  }

  private initGreenworkTypes() {
    this.http.get(`/assets/steam/greenworks.json`).subscribe((r: any) => {
      let list1 = this.resolver;
      let list2 = [];
      for (let l1 of list1) {
        for (let r1 of r) {
          if (r1.list)
            for (let r2 of r1.list) {
              if (r2.key === l1.key)
                list2.push(l1);
            }
        }
      }
      let list3 = _.differenceWith(list1, list2, _.isEqual);
      let other = _.findLast(r, s => s.type === 'other');
      if (other && other.list.length === 0) {
        other.list = list3;
      }
      this.lists = r;
    });
  }

  submit() {
    let fs = nw.require('fs');
    // @ts-ignore
    let filename = `${nw.App.startPath}/src/assets/steam/greenworks.json`;
    fs.writeFileSync(filename, JSON.stringify(this.lists));
  }

  drop(event: CdkDragDrop<any>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
      transferArrayItem(
          event.previousContainer.data,
          event.container.data,
          event.previousIndex,
          event.currentIndex,
      );
    }
  }
}
